package com.jose;

import com.nimbusds.jose.JOSEObjectType;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.crypto.RSASSASigner;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.shaded.json.parser.JSONParser;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;

import java.security.interfaces.RSAPrivateKey;
import java.util.Date;

/**
 * @author daxue0929
 * @date 2022/9/1
 */

public class Generate {

    public static void main(String[] args) throws Exception {

        String key = "-----BEGIN RSA PRIVATE KEY-----\n" +
            "MIICXAIBAAKBgQDh90WsVHQF0xvteLxHyRIzsIDc1chCVS+6dSOOU8MMEHoyc/Gf\n" +
            "PvTlQzCcmckv5zWe5u1TGnwPxfFVWmdjqHd2F+IEBkjS3l2UMZhaaDx+BxE7JQB1\n" +
            "el0P/Tzemr9aUMX2oZ4uQ6rRqC22zAvJdXcZJGwP8UP4UQdC2MO198UTrwIDAQAB\n" +
            "AoGAO7prrTiJjnyV1jhitCre59DQzw6nJ3ly6ztJUbasSMUWN73T8T7n5q3S7KHt\n" +
            "vv7DeqQZuSy3/EdbGi+SQpJmOM7AMFh3zs/aEnGMDeBq1+iexEdSmJSPOegqIadH\n" +
            "iVViPOIIUHtGNNx+1sPXfRKK3tjkTavOM6RP0CgUG2vHLBECQQDztomXlxwYddlL\n" +
            "J8BUcFBjXi1jXrq27Pp8IZ5uFqjXe7c8AQqWXFAw/mxfBT53rPRKcgoRJDHa9zI2\n" +
            "NHnCHl3JAkEA7Vuuy8soWOs6ZVxwOA1fyg2hPWobPzi39BvM1y4SH5QxabRVUo8v\n" +
            "7LvTd6WwXVSbwlReGUmXKfL5kW2IrEBBtwJAOR+C1o4rnqwYt13k3aXJodDUMKNm\n" +
            "fjPDbk7u9HzJLGCqDR1tXtraTPGFcywmfSSDyeM66tOh/+HK2huoolA9yQJBAK7J\n" +
            "9jWC3KpmRrF/2e+dAa4kTVmRepEa7nPnyPeoqJXyplSmBLLwWKVnR3lzXSXNeYoo\n" +
            "YMcUZynwEJJka+IUy48CQFmZFYWFlWLzYdLzQ502UxTd3YlnYXqa/C5CzgxuKHfU\n" +
            "FPKaoBfw2nH9J7G9Aqu3cDaIOnXoqY+oZTWSNafPBIg=\n" +
            "-----END RSA PRIVATE KEY-----\n";

        System.out.println(generateJWT(key));

    }

    public static String generateJWT(String jwkPrivateString) throws Exception {
        long now = System.currentTimeMillis();
        RSAPrivateKey privateKey = getPrivateKey(jwkPrivateString);


        JWTClaimsSet.Builder claimsBuilder = new JWTClaimsSet.Builder()
            .issuer("123456")
            .issueTime(new Date(now))
            .audience("contacts")
            .expirationTime(new Date(now + 60000000))  //Token的过期时间，此处为10分钟。
            .claim("", "");

        JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.parse("RS256"))
//            .keyID(kid)
            .type(JOSEObjectType.JWT)
            .build();
        SignedJWT signedJWT = new SignedJWT(header, claimsBuilder.build());
        signedJWT.sign(new RSASSASigner(privateKey));
        return signedJWT.serialize();
    }

    private static RSAPrivateKey getPrivateKey(String privateKey) throws Exception {
        Object privateKeyObj = new JSONParser(JSONParser.USE_HI_PRECISION_FLOAT |
            JSONParser.ACCEPT_TAILLING_SPACE).parse(privateKey);
        if (privateKeyObj instanceof com.nimbusds.jose.shaded.json.JSONObject) {
            com.nimbusds.jose.shaded.json.JSONObject jwtObject = (com.nimbusds.jose.shaded.json.JSONObject) privateKeyObj;
            // Find the RSA signing key
            if (jwtObject.get("use").equals("sig") && jwtObject.get("kty").equals("RSA")) {
                return RSAKey.parse(jwtObject).toRSAPrivateKey();
            }
        }
        return null;

    }
}
